package wan.moneybook;

import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import wan.moneybook.bean.Account;
import wan.moneybook.handler.Handler;

import com.ibatis.common.resources.Resources;

@SuppressWarnings("serial")
public class Controller extends HttpServlet {

	private final HashMap<String, Handler> handlerMap = new HashMap<String, Handler>();

	@Override
	public void init(ServletConfig config) throws ServletException {
		try {
			String resource = "wan/moneybook/handler/handler.properties";
			Reader reader = Resources.getResourceAsReader(resource);
			Properties prop = new Properties();
			prop.load(reader);
			for (Object obj : prop.keySet()) {
				String key = (String) obj;
				Handler handlerInstance = (Handler) Class.forName(prop.getProperty(key))
				.newInstance();
				handlerMap.put(key, handlerInstance);
			}
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String cmd = (request.getParameter("cmd") != null) ? request.getParameter("cmd") : "tabs";

		printParameter(request);

		String viewPage = null;
		Handler handler = handlerMap.get(cmd);
		if (handler != null) {
			try {
				viewPage = handler.process(request, response);
			} catch (Throwable e) {
				throw new ServletException(e);
			}
		}
		if (viewPage != null) {
			RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
			dispatcher.forward(request, response);
		}
	}

	@SuppressWarnings("unchecked")
	private void printParameter(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer().append(((Account)request.getSession().getAttribute("account")).getId())
		.append('\t').append(request.getRemoteHost()).append("\n\t");
		Enumeration en = request.getParameterNames();
		int size = 50;
		while (en.hasMoreElements()) {
			if (sb.length() > size) {
				sb.append("\n\t");
				size += 50;
			}
			String key = (String)en.nextElement();
			sb.append('[').append(key).append(":").append(request.getParameter(key)).append("], ");
		}
		System.out.println(sb.append('\n').toString());
	}


}
